package com.suredy.app.project.ctrl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.suredy.app.project.constants.ContractLevel;
import com.suredy.app.project.constants.DicKey;
import com.suredy.app.project.model.Contract;
import com.suredy.app.project.model.ContractMember;
import com.suredy.app.project.service.ContractMemberSrv;
import com.suredy.app.project.service.ContractSrv;
import com.suredy.core.ctrl.BaseCtrl;
import com.suredy.core.service.DictionarySrv;

/**
 * 合同表单控制器
 * 
 * @author VIVID.G
 * @since 2015-7-30
 * @version v0.1
 */
@Controller
@RequestMapping("/contract/form")
public class ContractFormCtrl extends BaseCtrl {

	private final static Logger log = LoggerFactory.getLogger(Contract.class);

	@Autowired
	private ContractSrv contractSrv;

	@Autowired
	private DictionarySrv dictionarySrv;

	@Autowired
	private ContractMemberSrv contractMemberSrv;

	@RequestMapping(value = "/edit-field", method = RequestMethod.POST)
	@ResponseBody
	public boolean editField(String id, String field, String data, String format) {
		try {
			Object val = this.stringToFieldValue(Contract.class, field, data, format);

			Map<String, Object> fields = new HashMap<String, Object>();

			fields.put(field, val);

			return this.contractSrv.updateFields(fields, "T.id=?", id) == 1;
		} catch (Exception e) {
			log.error("Edit field error.", e);
		}

		return false;
	}

	@RequestMapping(value = "/edit-member", method = RequestMethod.POST)
	@ResponseBody
	public boolean editMember(String id, ContractLevel level, String field, String data) {
		try {
			Object val = this.stringToFieldValue(ContractMember.class, field, data, null);

			Map<String, Object> fields = new HashMap<String, Object>();

			fields.put(field, val);

			Contract contract = new Contract();
			contract.setId(id);

			return this.contractMemberSrv.updateFields(fields, "T.level=? AND T.contract=?", level, contract) == 1;
		} catch (Exception e) {
			log.error("Edit field error.", e);
		}

		return false;
	}

	@RequestMapping(value = "/child", method = RequestMethod.GET)
	public String childContractForm(String id, String projId, Model model) {
		String view = "app/project/child-contract-form";

		if (StringUtils.isBlank(projId)) {
			model.addAttribute("noProjectId", true);
			return view;
		}

		Contract child = null;

		if (StringUtils.isBlank(id)) {
			// 新建
			child = new Contract();
			child.setType(Contract.TYPE_PAYMENT);
			child.setMainContract(false);
		} else {
			// 修改
			child = this.contractSrv.get(id);

			if (child == null || StringUtils.isBlank(child.getId())) {
				model.addAttribute("notFound", true);
				return view;
			}
		}

		model.addAttribute("projId", projId);
		model.addAttribute("orgName", this.getUser().getOrgName());
		model.addAttribute("data", child);
		model.addAttribute("customerCompany", this.projCustomerCompany());
		model.addAttribute("supplierCompany", this.projSupplierCompany());

		return view;
	}

	@RequestMapping(value = "/update-child", method = RequestMethod.POST)
	@ResponseBody
	public boolean createChildContract(Contract contract) {
		if (contract == null || contract.getProject() == null)
			return false;

		contract.setId(null);

		if (contract.getMembers() != null) {
			for (ContractMember m : contract.getMembers()) {
				m.setId(null);
				m.setContract(contract);
			}
		}

		contract = this.contractSrv.saveOrUpdate(contract);

		return contract != null && !StringUtils.isBlank(contract.getId());
	}

	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	@ResponseBody
	public boolean deleteContract(String id) {
		if (StringUtils.isBlank(id))
			return false;

		int count = this.contractSrv.deleteById(id);

		return count == 1;
	}

	private List<String> projCustomerCompany() {
		return this.dictionarySrv.getVals(DicKey.CUSTOMER_COMPANY);
	}

	private List<String> projSupplierCompany() {
		return this.dictionarySrv.getVals(DicKey.SUPPLIER_COMPANY);
	}

}
